package com.itheima.service.Impl;

import com.itheima.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendMailServiceImpl implements SendMailService {

    //创建邮件发送对象
    @Autowired
    private JavaMailSender mailSender;

    //设置邮件的主体信息
    private String from="1837295059@qq.com";
    private String to="927239465@qq.com";
    //设置主体
    private String subject="测试mail连通";
    //设置主体信息
//    private String context="<a href='https://www.baidu.com'>点开有惊喜</a>";
    private String context="<img src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F8326cffc1e178a82b9018131e84f648da97739124247&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655610673&t=576be60c169eeffdb5c8f10c748c22d9'>点开有惊喜</a>";

    //添加附件
    File file=new File("F:\\environment\\md笔记\\java学习路线\\SpringBoot\\5、2021新版SpringBoot2全套\\1.基础篇\\SpringBoot—资料\\SpringBoot—资料\\源代码\\springboot\\springboot_javamail\\src\\test\\java\\com\\itheima\\SpringbootJavamailApplicationTests.java");

    @Override
    public void sendSimpleMail() {
        //发送简单邮件
        //创建简单邮件对象
        SimpleMailMessage simpleMail=new SimpleMailMessage();
        //设置邮件的主体信息
        simpleMail.setFrom(from+"(小甜甜)");
        simpleMail.setTo(to);
        simpleMail.setSubject(subject);
        simpleMail.setText(context);


        //发送邮件
        mailSender.send(simpleMail);

    }


    /**
     * 发送复杂邮件：带附件，链接....
     */
    @Override
    public void sendMimeMail()  {


        try {
            MimeMessage mimeMessage=mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from+"(小甜甜)");
            helper.setTo(to);
            helper.setSubject(subject);

            helper.setText(context,true);
            //添加附件
            helper.addAttachment(file.getName(),file);
//            helper.addAttachment("图片",file1);
            mailSender.send(mimeMessage);

        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
